package light.head.controller.sys;

import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import light.head.config.ConfigParm;
import light.head.constant.Msg;
import light.head.constant.Parm;
import light.head.constant.Sys;
import light.head.constant.Url;
import light.head.dao.sys.OrganDAO;
import light.head.dao.sys.OrganDetailsDAO;
import light.head.dao.sys.OrganSynopsisAnnexDAO;
import light.head.dao.sys.OrganSynopsisDAO;
import light.head.dao.sys.UserInfoDAO;
import light.head.enm.RESULT;
import light.head.framework.base.SupporterController;
import light.head.model.FileInfo;
import light.head.model.Organ;
import light.head.model.OrganDetails;
import light.head.model.OrganSynopsis;
import light.head.model.OrganSynopsisAnnex;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 机构管理（系统管理员）
 */

@Controller
@RequestMapping(value = Url.C_ORGAN_ORGAN)
public class OrganOrganController extends SupporterController {

	private OrganDAO organDAO;
	private UserInfoDAO userDAO;
	private OrganDetailsDAO odsDAO;
	private OrganSynopsisDAO osDAO;
	private OrganSynopsisAnnexDAO osaDAO;
	private final static String organorgan_photo_path = "upload/organSynopsisPhoto/";
	private final static String organorgan_file_path = "upload/organSynopsisFile/";
	private final static String upload_path = "upload/organSynopsisAnnex/";

	@RequestMapping(Url.INIT)
	public ModelAndView tree(HttpServletRequest request, HttpServletResponse response) throws Exception {
		Organ o = organDAO.getOrgan(cu_organCode(request));
		if (null != o) {
			StringBuffer tree = new StringBuffer();
			if (!o.getDeleted()) {
				tree.append("p.add('" + o.getCode() + "','-1','" + o.getName() + "');");
				aidTree(tree, o.getSonList());
			}

			request.setAttribute(Parm.TREE, tree);
			request.setAttribute(Parm.ORGAN, o);
		}
		return new ModelAndView(Url.ORGAN_ORGAN_TREE);
	}

	private void aidTree(StringBuffer tree, List<Organ> list) {
		if (null == tree || null == list || list.size() == 0)
			return;
		for (Organ o : list) {
			if (!o.getDeleted() && o.getCode() != o.getPc()) {
				tree.append("p.add('" + o.getCode() + "','" + o.getPc() + "','" + o.getName() + "');");
				aidTree(tree, o.getSonList());
			}
		}
	}

	@RequestMapping(Url.AID_EDIT)
	public ModelAndView edit(Integer code, Integer pc, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null != code) {
			Organ cbi = organDAO.getOrgan(code);
			if (null != cbi) {
				OrganDetails ods = odsDAO.getByOc(cbi.getCode());
				OrganSynopsis os = osDAO.getByOc(cbi.getCode());
				cbi.setDetails(ods);	// 详情
				cbi.setSynopsis(os);	// 简介
				request.setAttribute(Parm.ORGAN, cbi);
				if(ods != null){
					StringBuffer str = new StringBuffer("[");
					str.append("{\"info\":");
					str.append("[");
					str.append("\"<a href='" + ConfigParm.getContextPath() + "organindex.html?code="+ cbi.getCode() + "'>" + cbi.getName() + "</a>\",");
					str.append("\"电话:" + ((null == ods.getPhone()) ? "暂无" : ods.getPhone()) + "地址:" + ((null == ods.getAddress()) ? "暂无" : ods.getAddress()) + "\"");
					str.append("],");
					str.append("\"lng\":\"" + ((null == ods.getLongitude()) ? "non" : ods.getLongitude()) + "\",");
					str.append("\"lat\":\"" + ((null == ods.getLatitude()) ? "non" : ods.getLatitude()) + "\"},");
					str.deleteCharAt(str.length() - 1).append("]");
					request.setAttribute(Parm.ORGANDETAIL, str.toString());
					if(ods.getLongitude() != null && ods.getLatitude() != null){
						request.setAttribute(Parm.LONGITUDE, ods.getLongitude());
						request.setAttribute(Parm.LATITUDE, ods.getLatitude());
					}
				}
			}
		} else if (null != pc) {
			Organ parent = organDAO.getOrgan(pc);
			if (null != parent) {
				Organ o = new Organ();
				o.setPc(pc);
				o.setPn(parent.getName());
				o.setOtc(parent.getOtc());
				request.setAttribute(Parm.ORGAN, o);
			}
		}
		List<OrganSynopsisAnnex> list = osaDAO.getAnnexList4(code);
		if(list != null && list.size() != 0){
			for(OrganSynopsisAnnex osa : list){
				if(osa.getType() != null && osa.getType() == 1){
					request.setAttribute(Parm.YYLIST1, osa);
				}else if(osa.getType() != null && osa.getType() == 2){
					request.setAttribute(Parm.YYLIST2, osa);
				}else if(osa.getType() != null && osa.getType() == 3){
					request.setAttribute(Parm.YYLIST3, osa);
				}
			}
		}
		request.setAttribute(Parm.LIST, list);
		String userList = userDAO.userList(cu_organCode(request));
		request.setAttribute(Parm.USER_LIST, userList);

		return new ModelAndView(Url.ORGAN_ORGAN_AID_EDIT);
	}

	@Transactional(rollbackFor = Exception.class)
	@RequestMapping(Url.SAVE)
	public void save(Organ cbi, HttpServletRequest request, HttpServletResponse response) throws Exception {
		RESULT result = RESULT.ERROR;
		if (null == cbi.getPc()) {
			print(response, Msg.PARAMETER_ERROR);	// 父机构不能为空
			return;
		}
		if (null != cbi.getCode() && cbi.getPc().intValue() == cbi.getCode().intValue()) {
			print(response, Msg.FAILURE);			// 父机构不能选择自己
			return;
		}
		if (cbi.getCode() != null) {
			result = organDAO.update(cbi);
			// 修改详情, 如果详情为空，则新增
			result = odsDAO.update(cbi.getDetails());
			if (RESULT.NOT_FIND == result || RESULT.PARAMETER_ERROR == result) {
				cbi.getDetails().setOc(cbi.getCode());
				result = odsDAO.add(cbi.getDetails());
			}
			// 修改简介,如果简介为空就新增
			result = osDAO.update(cbi.getSynopsis());
			if (RESULT.NOT_FIND == result) {
				cbi.getSynopsis().setOc(cbi.getCode());
				cbi.getSynopsis().setCt(new Date());
				cbi.getSynopsis().setCu(cu_code(request));
				result = osDAO.add(cbi.getSynopsis());
			}
			
		}else{
			//添加
			cbi.setDeleted(false);
			cbi.setCu(cu_code(request));
			result = organDAO.add(cbi);
			if(result == RESULT.SUCCESS){
				cbi.getSynopsis().setCt(new Date());
				cbi.getSynopsis().setOc(cbi.getCode());
				osDAO.add(cbi.getSynopsis());
				cbi.getDetails().setOc(cbi.getCode());
				result = odsDAO.add(cbi.getDetails());
			}
		}
		//图片
		if(result == RESULT.SUCCESS){
			List<Object> noDelCodes = new ArrayList<Object>();
			if (null != cbi.getList() && cbi.getList().size() > 0) {
				for (OrganSynopsisAnnex osa :  cbi.getList()) {
					if(null == osa.getCode())	// 编号为空的不在这里添加（因为有可能是删除的或新增的）
						continue;
					if (null != osa.getCode())
						noDelCodes.add(osa.getCode());
				}
			}
			OrganSynopsisAnnex osa = null;
			if(cbi.getList() != null){
				for(OrganSynopsisAnnex temp: cbi.getList()){
					
					if(temp.getCode() == null){
						// 因为新增的都会有以下判断的三个参数，如果是删除的就没有这三个参数
						if(null == temp.getSn() && null == temp.getExt() && null == temp.getName())
							continue;
						/*List<OrganSynopsisAnnex> osd =;*/
						osa = new OrganSynopsisAnnex();
						osa.setCover(temp.getCover());
						osa.setExt(temp.getExt());
						osa.setDeleted(false);
						osa.setOdc(cbi.getCode());
						osa.setName(temp.getName());
						osa.setSize(temp.getSize());
						osa.setType(temp.getType());
						osa.setSn(temp.getSn());
						result = osaDAO.add(osa);
						noDelCodes.add(osa.getCode());
					}else{
						OrganSynopsisAnnex temp1 = osaDAO.get(temp.getCode());
						temp1.setCover(temp.getCover());
						result = osaDAO.upd(temp1);
					}
				}
			}
			organDAO.deleteAnnexNotInCodes(cbi.getCode(), noDelCodes);
		}
		if (RESULT.SUCCESS == result) {
			organDAO.loadAll();
			print(response, Msg.SUCCESS);
		} else
			print(response, Msg.ERROR);
	}

	@RequestMapping(Url.DELETE)
	public void delete(Integer code, HttpServletRequest request, HttpServletResponse response) throws Exception {
		if (null == code) {
			print(response, Msg.PARAMETER_ERROR);
			return;
		}
		Organ o = organDAO.get(code);
		if (null == o) {
			print(response, Msg.NOT_FIND);
			return;
		}
		o.setDeleted(true);
		if (organDAO.upd(o) == RESULT.SUCCESS) {
			organDAO.loadAll();
			print(response, Msg.SUCCESS);
		}
	}


	/** 下面几个方法是辅助其他模块查询用户时使用 */
	@RequestMapping(Url.AID_INIT)
	public ModelAndView aidInit(HttpServletRequest request, HttpServletResponse response) throws Exception {
		request.setAttribute(Parm.ID, request.getParameter(Parm.ID));
		request.setAttribute(Parm.NAME, request.getParameter(Parm.NAME));

		Integer code = cu_organCode(request);
		if (null != code) {
			List<Organ> list = organDAO.getAll();
			Organ o = findOgranByCode(code, list);
			if (null != o) {
				StringBuffer tree = new StringBuffer();
				if (!o.getDeleted()) {
					tree.append("p.add('" + o.getCode() + "','-1','" + o.getName() + "');");
					aidTree(tree, o.getSonList());
				}
				request.setAttribute(Parm.TREE, tree);
				request.setAttribute(Parm.ORGAN, o);
			}
		}
		return new ModelAndView(Url.ORGAN_ORGAN_AID_INIT);
	}

	private Organ findOgranByCode(Integer code, List<Organ> list) {
		if (null != code && null != list && list.size() > 0) {
			for (Organ o : list) {
				if (code.intValue() == o.getCode().intValue()) {
					return o;
				} else {
					Organ temp = findOgranByCode(code, o.getSonList());
					if (null != temp)
						return temp;
				}
			}
		}
		return null;
	}
	
	// 上传多个文件
	@Transactional
	@RequestMapping(Url.UPLOADS)
	public void uploads(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = multipartRequest.getFiles("files");
		StringBuffer result = new StringBuffer("");
		if (null != files && files.size() > 0) {
			String name = null;
			String ext = null;
			String uuid = null;
			String path = null;
			String savePath = null;
			UUID u = null;
			for (MultipartFile mf : files) {
				name = mf.getOriginalFilename();
				if (isNotNull(name)) {
					ext = name.substring(name.lastIndexOf('.') + 1);
					if (!ext.toUpperCase().equals(Sys.JPG)
							&& !ext.toUpperCase().equals(Sys.GIF)
							&& !ext.toUpperCase().equals(Sys.JPEG)
							&& !ext.toUpperCase().equals(Sys.BMP)
							&& !ext.toUpperCase().equals(Sys.PNG)) {
						print(response, Msg.J_FILE_TYPE_ERROR);
						return;
					}
					name = name.substring(0, name.lastIndexOf('.'));
					u = UUID.randomUUID();
					uuid = u.toString().replace("-", "");
					path = upload_path + uuid + Sys.DOT + ext;
					savePath = ConfigParm.getProjectPath() + path;
					FileOutputStream fo;
					int size = 0;

					try {
						fo = new FileOutputStream(savePath);
						size = mf.getBytes().length;
						fo.write(mf.getBytes());
						fo.close();
					} catch (Exception e) {
						print(response, Msg.ERROR);
						e.printStackTrace();
					}

					FileInfo f = new FileInfo();
					f.setDeleted(false);
					f.setExt(ext);
					f.setName(name);
					f.setUuid(uuid);
					f.setCt(new Date());
					f.setType(Sys.B_TWO);
					f.setModule(Parm.ORGANSYNOPSISANNEX);
					f.setCu(cu_code(request));
					f.setOc(cu_organCode(request));
					f.setSize(size);
					organDAO.add(f);
					result.append("{\"name\":\"" + name + "\",\"code\":\""+ f.getCode() + "\",\"ext\":\"" + ext+ "\",\"size\":\"" + size + "\",\"path\":\"" + uuid+ Sys.DOT + ext + "\"},");
				}
			}
			result.insert(0, "{\"result\":\"success\",\"list\":[").deleteCharAt(result.length() - 1).append("]}");
			print(response, result.toString());
		} else {
			result.append("{\"result\":\"not_find_file\"}");
		}
	}
	
	// 单个文件保存
		@Transactional
		@RequestMapping(Url.UPLOAD)
		public void upload(HttpServletRequest request, HttpServletResponse response) {
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile pohto = multipartRequest.getFile(Parm.UPLOAD);
			String type = request.getParameter(Parm.TYPE);
			String name = pohto.getOriginalFilename();
			if (isNotNull(name)) {
				String ext = name.substring(name.lastIndexOf(Sys.DOT) + 1);
				if (!ext.toUpperCase().equals(Sys.JPG)
						&& !ext.toUpperCase().equals(Sys.GIF)
						&& !ext.toUpperCase().equals(Sys.JPEG)
						&& !ext.toUpperCase().equals(Sys.BMP)
						&& !ext.toUpperCase().equals(Sys.PNG)
						&& !ext.toUpperCase().equals(Sys.XLSX)
						&& !ext.toUpperCase().equals(Sys.XLS)
						&& !ext.toUpperCase().equals(Sys.DOCX)
						&& !ext.toUpperCase().equals(Sys.DOC)
						&& !ext.toUpperCase().equals(Sys.PDF)
						&& !ext.toUpperCase().equals(Sys.PPT)
						&& !ext.toUpperCase().equals(Sys.RAR)
						&& !ext.toUpperCase().equals(Sys.ZIP)) {
					print(response, Msg.J_FILE_TYPE_ERROR);
					return;
				}
				name = name.substring(0, name.lastIndexOf(Sys.DOT));

				UUID u = UUID.randomUUID();
				String uuid = u.toString().replace("-", "");
				String path = (type.equals(Sys.FILE) ? organorgan_file_path : organorgan_photo_path) + uuid + Sys.DOT + ext;
				String savePath = ConfigParm.getProjectPath() + path;
				FileOutputStream fo;
				int size = 0;
				try {
					fo = new FileOutputStream(savePath);
					size = pohto.getBytes().length;
					fo.write(pohto.getBytes());
					fo.close();
				} catch (Exception e) {
					print(response, Msg.J_ERROR);
					e.printStackTrace();
					throw new RuntimeException();
				}

				FileInfo f = new FileInfo();
				f.setDeleted(false);
				f.setExt(ext);
				f.setName(name);
				f.setUuid(uuid);
				f.setCt(new Date());
				if (type.equals(Sys.FILE)) {
					f.setType(Sys.B_ONE);
					f.setModule(Parm.ORGANSYNOPSISFILE);
				} else {
					f.setType(Sys.B_TWO);
					f.setModule(Parm.ORGANSYNOPSISPHOTO);
				}

				f.setCu(cu_code(request));
				f.setOc(cu_organCode(request));
				f.setSize(size);
				organDAO.add(f);

				StringBuffer result = new StringBuffer();
				result.append("<script type=\"text/javascript\">");
				if (isNotNull(path)) {
					result.append("window.parent.CKEDITOR.tools.callFunction("
							+ request.getParameter("CKEditorFuncNum") + ",'" + path
							+ "',''" + ")");
					result.append("</script>");
					result.append(path);
				} else {
					result.append("alert(\"上传失败，文件类型需要jpg、gif或png\")");
					result.append("</script>");
				}
				response.setHeader("Content-Type", "text/html; charset=UTF-8");
				print(response, result.toString());

			} else {
				print(response, Msg.J_ERROR);
			}
		}
	@Autowired
	public void setOrganDAO(OrganDAO organDAO) {
		this.organDAO = organDAO;
	}

	@Autowired
	public void setUserDAO(UserInfoDAO userDAO) {
		this.userDAO = userDAO;
	}

	@Autowired
	public void setOdsDAO(OrganDetailsDAO odsDAO) {
		this.odsDAO = odsDAO;
	}

	@Autowired
	public void setOsDAO(OrganSynopsisDAO osDAO) {
		this.osDAO = osDAO;
	}
	@Autowired
	public void setOsaDAO(OrganSynopsisAnnexDAO osaDAO) {
		this.osaDAO = osaDAO;
	}
}
